﻿using System;
using System.Collections.Generic;
using System.Web.Services.Protocols;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;

namespace MedicWeb.forms.Editors.Directory {
    public partial class JobEdit : SessionPage {

        private Job job;

        protected void Page_Load(object sender, EventArgs e) {
            Form.Action = ResolveUrl("~/forms/Editors/Directory/JobEdit.aspx");
            string id = Request.QueryString["id"];
            string reg = Request.QueryString["category"];
            var ms = new MainService();
            FillCombo(comboJobCategory, ms.GetJobCategoryList(GetSession(), true));
            if (reg != null) {
                Form.Action += "?category="+reg;
            }
            if (id != null) {
                Form.Action += (reg == null ? "?" : "&") + "id=" + id;
                job = ms.LoadJob(GetSession(), Convert.ToInt32(id));
            } else {
                job = new Job();
                if (reg != null) {
                    JobCategory category = ms.LoadJobCategory(GetSession(), Convert.ToInt32(reg));
                    job.JobCategory = category;
                }
            }
            if (job.JobCategory == null) {
                job.JobCategory = new JobCategory();
            }
            if (!IsPostBack) {
                tfJob.Text = job.Title;
                SelectInCombo(comboJobCategory, job.JobCategory);
                if (reg != null) {
                    comboJobCategory.Enabled = false;
                }
            }
        }

        private static void SelectInCombo(ListControl combo, DirectorySimpleItem selectedValue) {
            if (selectedValue != null) {
                try {
                    combo.SelectedValue = "" + selectedValue.Id;
                } finally { }
            }
        }
        private static void FillCombo(ListControl combo, IEnumerable<DirectorySimpleItem> items) {
            foreach (var item in items) {
                var listItem = new ListItem(item.Title, "" + item.Id);
                listItem.Attributes["type"] = item.GetType().Name;
                combo.Items.Add(listItem);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            try {
                job.JobCategory.Id = Convert.ToInt32(comboJobCategory.SelectedValue);
                job.Title = tfJob.Text;
                var ms = new MainService();
                job = ms.SaveJob(GetSession(), job);
                Session["success"] = "Изменения сохранены успешно";
            } catch (Exception ex) {

                if (ex.InnerException is SoapException
                    && ((SoapException)ex.InnerException).Detail.InnerText == "AuthorizationException") {
                    throw ex;
                } else {
                    Session["error"] = "Ошибка сохранения";
                }
            }
        }
    }
}